/*
 * @Author: zhangyun
 * @Date: 2021-04-27 13:39:24
 * @LastEditors: zhangyun
 * @LastEditTime: 2021-04-27 16:08:09
 * @Desc:
 */
const express = require('express')
const router = express.Router()
const _ = require('lodash')
const articleModel = require('../model/articleModel')
const message = require('../utils/message')

router.get('/', (req, res) => {
  const { searchVal, id } = req.query

  if (searchVal) {
  } else if (id) {
    articleModel
      .findById(id)
      .then((result) => {
        res.status(200).send(message(200, '查询成功', result))
      })
      .catch((err) => {
        console.log('idea list', err)
        res.status(400).send(message(400, '查询失败'))
      })
  } else {
    articleModel
      .find()
      .then((result) => {
        res.status(200).send(message(200, '查询成功', result.reverse()))
      })
      .catch((err) => {
        console.log('idea list', err)
        res.status(400).send(message(400, '查询失败'))
      })
  }
})

router.post('/', (req, res) => {
  const { img, title, time, detail, creator } = req.body
  articleModel
    .insertMany({
      img,
      title,
      time,
      detail,
      creator,
    })
    .then((result) => {
      res.status(200).send(message(200, '创建成功'))
    })
    .catch((err) => {
      console.log('idea list', err)
      res.status(400).send(message(400, '创建失败'))
    })
})

router.delete('/', (req, res) => {
  const { id } = req.query
  articleModel
    .findByIdAndDelete(id)
    .then((result) => {
      res.status(200).send(message(200, '删除成功'))
    })
    .catch((err) => {
      console.log('idea list', err)
      res.status(400).send(message(400, '删除失败'))
    })
})

module.exports = router
